package zzg.study.download;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import zzg.study.ext.ByteArrayResponseExtractor;
import zzg.study.support.DownloadProgressPrinter;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @Classname SimpleDownloader
 * @Description 简单下载，这种方式会将文件的字节数组全部放入内存中
 * @Date 2024/2/21 22:38
 * @Author zhuzhenguo
 */
public class SimpleDownloader extends AbstractDownloader {

    public SimpleDownloader(DownloadProgressPrinter downloadProgressPrinter) {
        super(downloadProgressPrinter);
    }

    public SimpleDownloader() {
        super(DownloadProgressPrinter.defaultDownloadProgressPrinter());
    }

    @Override
    protected void doDownload(String fileUrl, String dir, String fileName, HttpHeaders headers) throws IOException {
        String filePath = dir + File.separator + fileName;
        byte[] body = restTemplate.execute(fileUrl, HttpMethod.GET, null,
                new ByteArrayResponseExtractor(downloadProgressPrinter));
        Files.write(Paths.get(filePath), Objects.requireNonNull(body));
    }

}
